#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>

pthread_mutex_t mutex;

int number = 0;

void* func_add_A(void *arg) {
    for (int i = 0; i < 500000; ++i) {
        pthread_mutex_lock(&mutex);
        int cur = number;
        ++cur;
        number = cur;
        pthread_mutex_unlock(&mutex);
    }
}
void* func_add_B(void *arg) {
    for (int i = 0; i < 500000; ++i) {
        pthread_mutex_lock(&mutex);
        int cur = number;
        ++cur;
        number = cur;
        pthread_mutex_unlock(&mutex);
    }
}

int main() {
    pthread_t tid1, tid2;
    pthread_mutex_init(&mutex, NULL);   // 虽然这里不用这个也能实现一样的效果
    // 查了一下好像是清零锁对象内存区域避免锁对象有随机值带来的不确定行为

    pthread_create(&tid1, NULL, func_add_A, NULL);
    pthread_create(&tid2, NULL, func_add_B, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_mutex_destroy(&mutex);
    printf("%d\n", number);
}

